var totalCount;

/*发送消息*/
function send(headSrc, str, time) {
    var html = "<div class='send'><div class=\"time\">" + time + "</div><div class='msg'><img src=" + headSrc + " />" +
        "<p><i class='msg_input'></i>" + str + "</p></div></div>";
    upView(html);
}

/*接受消息*/
function show(headSrc, str, time) {
    var html = "<div class='show'><div class=\"time\">" + time + "</div><div class='msg'><img src=" + headSrc + " />" +
        "<p><i class='msg_input'></i>" + str + "</p></div></div>";
    upView(html);
}

/*更新视图*/
function upView(html) {
    $('.message').append(html);
    $('body').animate({scrollTop: $('.message').outerHeight() - window.innerHeight}, 200)
}

function sj() {
    return parseInt(Math.random() * 10)
}
//格式化时间
function CurentTime(date) {
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    var hh = date.getHours();
    var mm = date.getMinutes();
    var clock = year + "-";
    if (month < 10)
        clock += "0";
    clock += month + "-";
    if (day < 10)
        clock += "0";
    clock += day + " ";
    if (hh < 10)
        clock += "0";
    clock += hh + ":";
    if (mm < 10) clock += '0';
    clock += mm;
    return clock;
}
//格式化时间
function CurentTimeWithSeconds(date) {
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    var hh = date.getHours();
    var mm = date.getMinutes();
    var ss = date.getSeconds();
    var clock = year + "-";
    if (month < 10)
        clock += "0";
    clock += month + "-";
    if (day < 10)
        clock += "0";
    clock += day + " ";
    if (hh < 10)
        clock += "0";
    clock += hh + ":";
    if (mm < 10) clock += '0';
    clock += mm + ":";
    if (ss < 10) clock += "0";
    clock += ss;
    return clock;
}

//跳转到底部
function toButtom() {
    var c = window.document.body.scrollHeight;
    window.scroll(0, c);
}

$(function () {
    $('.footer').on('keyup', 'input', function () {
        if ($(this).val().length > 0) {
            $(this).next().css('background', '#114F8E').prop('disabled', true);

        } else {
            $(this).next().css('background', '#ddd').prop('disabled', false);
        }
    })
    var param = getParams();
    var sendUser = JSON.parse(sessionStorage.getItem("user"));
    var acceptUser;

    //获取私信人的个人信息数据
    $.get("/userChats",{acceptUserId:param.id},function (data) {
        acceptUser = data;
        $("#userName").html(data.acceptUser.nickName);
        $("#userIndex").click(function () {
            window.location.href = "/userProfiles.html?id=" + data.acceptUser.id;
        });
    });
    //获取聊天记录
    $.get("/userChats/messages",{sendId:sendUser.id,currentId:param.id}, function (data) {
        console.log(data);
        $.each(data, function (index, value) {
            if (value.myUser.id == sendUser.id) {
                $(".message").prepend("<div class=\"show\">\n" +
                    "        <div class=\"time\">" + CurentTime(new Date(value.createTime)) + "</div>\n" +
                    "        <div class=\"msg\">\n" +
                    "            <img src=" + value.myUser.headImgUrl + " alt=\"\"/>\n" +
                    "            <p>" + value.message + "</p>\n" +
                    "        </div>\n" +
                    "    </div>");
            } else {
                $(".message").prepend("<div class=\"send\">\n" +
                    "        <div class=\"time\">" + CurentTime(new Date(value.createTime)) + "</div>\n" +
                    "        <div class=\"msg\">\n" +
                    "            <img src=" + value.myUser.headImgUrl + " alt=\"\"/>\n" +
                    "            <p>" + value.message + "</p>\n" +
                    "        </div>\n" +
                    "    </div>");
            }
        });
        toButtom();
    });
    var sendObj = { };
    //当前登录用户
    myUserId = sendUser.id;
    //聊天的用户
    acceptUserId = param.id;
    //发送信息
    $("#sendBtn").click(function () {
        $message = $("#message");
        var message = $message.val();
        if (message.length === 0) return;
        show(sendUser.headImgUrl, $message.val(), CurentTime(new Date()));
        toButtom();
        message = message;
        sendObj={
            "myUser.id":myUserId,
            "acceptUser.id":acceptUserId,
            "message":message
        }
        //可能是保存
        $.post("/userChats", sendObj);
        $message.val("");
        $message.next().css('background', '#ddd').prop('disabled', false);
    });
   /* //设置已读
    $.ajax({
        type: "PUT",
        url: "/userChats/" + sendObj.sendUserId + "/" + sendObj.acceptUserId
    })*/;

    var newTime = CurentTimeWithSeconds(new Date());

   /* //定时器获取新信息
    function getNewMessage() {
        $.get("/userChats/users/" + sendUser.id + "/" + param.id + "/" + newTime, function (data) {
            if (data.length > 0) {
                $.each(data, function (index, value) {
                    send(value.sendUser.headImgUrl, value.message, CurentTime(new Date(value.sendTime)));
                });
                toButtom();
                newTime = CurentTimeWithSeconds(new Date());
            }
        });
    }*/
    $.get("/userChats/counts",{sendId:sendUser.id,currentId:param.id},function (data) {
        totalCount=data;
    })
    //定时器获取新信息
    function getNewMessage() {
        $.get("/userChats/counts",{sendId:sendUser.id,currentId:param.id},function (data) {
            if (data>totalCount){
                $.get("/userChats/newMessages",{sendId:sendUser.id,currentId:param.id}, function (data) {
                    if (data.length > 0) {
                        $.each(data, function (index, value) {
                            send(value.myUser.headImgUrl, value.message, CurentTime(new Date(value.createTime)));
                        });
                        toButtom();
                        newTime = CurentTimeWithSeconds(new Date());
                    }
                });
            }
            totalCount=data;
        })

    }
    window.setInterval(getNewMessage, 2000);//每3秒查询最新消息
});
